package com.bobo.demo.Thread.sync;

import java.util.concurrent.locks.ReentrantLock;

public class TestLock {
    public static void main(String[] args) {
        TestBuyTickets t =  new TestBuyTickets();
        new Thread(t,"黄牛党张三").start();
        new Thread(t,"学生党李四").start();
        new Thread(t,"手慢党赵六").start();
    }

}

class TestBuyTickets implements Runnable {

    int ticketNums = 10;

    private final ReentrantLock lock = new ReentrantLock();

    @Override
    public void run() {
        while(true) {
            lock.lock();//lock不能写在try里面 这是规范
            if(ticketNums <= 0){
                break;
            } else {
                try {
                    Thread.sleep(500);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println(Thread.currentThread().getName()+"抢到了第"+ticketNums--+"张票");
            }
            lock.unlock();
        }

    }
}